﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sitecore.Web.UI.Pages;
using Sitecore.Web.UI.HtmlControls;
using Sitecore.Diagnostics;
using Sitecore.Web;
using Sitecore.ChangesTracker.Archiving;
using Sitecore.Data.Archiving;
using Sitecore.Data.Templates;
using Sitecore.Data;

namespace Sitecore.ChangesTracker.UI
{
    public class TemplateComparer : DialogForm
    {
        protected Scrollbox Items;
        Guid archivalId;

        public Guid ArchivalId
        {
            get 
            {
                if (this.archivalId == null || this.archivalId.Equals(Guid.Empty))
                {
                    string id = WebUtil.GetQueryString("arcid");
                    Assert.ArgumentNotNullOrEmpty(id, "archivalId");
                    this.archivalId = new Guid(id);
                }
                return this.archivalId; 
            }
            
        }
        string archiveName;

       
        ChangeTrackerArchive archive;

       
        ArchivedTemplate template;
        List<ID> rendered = new List<ID>();

        public ChangeTrackerArchive Archive
        {
            get
            {
                if (this.archive == null || this.archive.Name.Equals(this.ArchiveName, StringComparison.OrdinalIgnoreCase))
                {
                    this.archive = ((ChangeTrackerArchive)((ChangeTrackerArchiveProvider)ArchiveManager.Providers["changetracker"]).GetArchive(this.ArchiveName, Sitecore.Context.ContentDatabase));
                }
                return this.archive;
            }
        }

        public string ArchiveName
        {
            get 
            { 
                if(string.IsNullOrEmpty(this.archiveName))
                {
                    this.archiveName=WebUtil.GetQueryString("arcName", "changetracker");
                }
                return this.archiveName; 
            }
           
        }
        protected override void OnLoad(EventArgs e)
        {
            Assert.ArgumentNotNull(e, "e");
            base.OnLoad(e);
            if (!Context.ClientPage.IsEvent)            
            {
                
                template = this.Archive.GetArchivedTempate(ArchivalId, true);
                Assert.IsNotNull(template, "archived template cannot be null");
                foreach (ArchivedItem section in template.Sections)
                {
                    BuildSection(section,ID.Null);
                }
                foreach (TemplateSection s in template.CurrentSections)
                {
                    if(!rendered.Contains(s.ID))
                    {
                        BuildSection(null, s.ID);
                    }
                }
            }
        }


        void BuildSection(ArchivedItem section, ID sectionId)
        {
            Guid sId = Guid.Empty;
            string sName = string.Empty;
            if (section != null)
            {
                rendered.Add(ID.Parse(section.ItemId));
                sId = section.ItemId;
                sName = section.Name;
            }
            else
            {
                sId = sectionId.ToGuid();
                sName = "Section has been added after control point creation";
            }
                Border b = new Border();
                b.Class = "scEditorSectionCaptionExpanded";
                b.ID = "Section_" + sId.ToString();
                b.Attributes.Add("ondblclick", "javascript:scContent.toggleSection('" + b.ID + "','" + sName + "')");
                Label l = new Label() { Header = sName };
                if (section == null)
                {
                    l.Style.Add("color", "red");
                }
                TemplateSection currentsection = template.CurrentSections.FirstOrDefault(s => s.ID.ToGuid() == sId);

                Label cl = new Label();
                if (currentsection != null)
                {
                    cl.Header = currentsection.Name;
                }
                else
                {
                    cl.Header = "Section has been deleted.";
                    cl.Style.Add("color", "red");
                }
                l.Float = "right";
                b.Controls.Add(l);
                b.Controls.Add(cl);
                Items.Controls.Add(b);
                Border b2 = new Border();
                Border field = new Border();
                Border cfield = new Border();

                if (UIUtil.IsIE())
                {
                    cfield.Style.Add("display", "inline");
                }
                else
                {
                    cfield.Style.Add("display", "inline-block");
                }

                cfield.Width = new System.Web.UI.WebControls.Unit(50, System.Web.UI.WebControls.UnitType.Percentage);
                field.Width = new System.Web.UI.WebControls.Unit(50, System.Web.UI.WebControls.UnitType.Percentage);
                if (UIUtil.IsIE())
                {
                    field.Style.Add("display", "inline");
                }
                else
                {
                    field.Style.Add("display", "inline-block");
                }

                foreach (ArchivedItem item in template.Fields.Where(i => i.ParentId == sId))
                {
                    BuildField(cfield, field, item);
                }
                foreach (TemplateField tfield in template.CurrentFields.Where(f => f.Section.ID.ToGuid() == sId))
                {
                    if (!rendered.Contains(tfield.ID))
                    {
                        BuildField(cfield, field, null, tfield.ID);
                    }
                }
                b2.Controls.Add(field);
                b2.Controls.Add(cfield);
                Items.Controls.Add(b2);
           
        }

        void BuildField(Border Control, Border ControlArchived, ArchivedItem item, ID fieldId=null)
        {
            
            Border field = new Border();
            
            Border archivedfield = new Border();
           
            if (item != null)
            {
                rendered.Add(ID.Parse(item.ItemId));
                Edit name = new Edit() { Disabled = true, Value = item.Name };
                name.ID = "name+" + item.ItemId.ToString() + "_archived";
                Edit type = new Edit() { Disabled = true, Value = item.Fields.First(f => f.FieldId == TemplateFieldIDs.Type.ToGuid()).Value };
                type.ID = "type_" + item.ItemId.ToString() + "_archived";
                Checkbox shared = new Checkbox() { Header = "Shared; ", Disabled = true };
                shared.ID = "shared_" + item.ItemId.ToString() + "_archived";
                Checkbox unversioned = new Checkbox() { Header = "Unversioned; ", Disabled = true };
                unversioned.ID = "unversioned_" + item.ItemId.ToString() + "_archived";
                Checkbox blob = new Checkbox() { Header = "Blob; ", Disabled = true };
                blob.ID = "blob_" + item.ItemId.ToString() + "_archived";
                ArchivedField sharedField = item.Fields.FirstOrDefault(f => f.FieldId == TemplateFieldIDs.Shared.ToGuid());
                if (sharedField != null)
                {
                    shared.Checked = sharedField.Value == "1";
                }
                else
                {
                    shared.Checked = false;
                }
                ArchivedField unversionedField = item.Fields.FirstOrDefault(f => f.FieldId == TemplateFieldIDs.Unversioned.ToGuid());
                if (unversionedField != null)
                {
                    unversioned.Checked = unversionedField.Value == "1";
                }
                else
                {
                    unversioned.Checked = false;
                }
                ArchivedField blobField = item.Fields.FirstOrDefault(f => f.FieldId == TemplateFieldIDs.Blob.ToGuid());
                if (blobField != null)
                {
                    blob.Checked = blobField.Value == "1";
                }
                else
                {
                    blob.Checked = false;
                }

                archivedfield.Controls.Add(name);
                archivedfield.Controls.Add(type);
                archivedfield.Controls.Add(shared);
                archivedfield.Controls.Add(unversioned);
                archivedfield.Controls.Add(blob);
            }
            else
            {
                Label noArchivedField = new Label() { Header = "This field was added after control point creation." };
                noArchivedField.Style.Add("color", "red");
                noArchivedField.ID = "noField_" + new Guid().ToString() + "_archived";
                archivedfield.Controls.Add(noArchivedField);
            }



            ID id = item == null ? fieldId : ID.Parse(item.ItemId);
            TemplateField currentField = template.CurrentFields.FirstOrDefault(f => f.ID == id);
            if (currentField != null)
            {
                Edit cname = new Edit() { Disabled = true };
                cname.ID = "cname" + id.ToString();
                Edit ctype = new Edit() { Disabled = true };
                ctype.ID = "ctype_" + id.ToString();
                Checkbox cshared = new Checkbox() { Header = "Shared; ", Disabled = true };
                cshared.ID = "cshared_" + id.ToString();
                Checkbox cunversioned = new Checkbox() { Header = "Unversioned; ", Disabled = true };
                cunversioned.ID = "cunversioned_" + id.ToString();
                Checkbox cblob = new Checkbox() { Header = "Blob; ", Disabled = true };
                cblob.ID = "cblob" + id.ToString();
                if (currentField != null)
                {
                    cname.Value = currentField.Name;
                    ctype.Value = currentField.Type;
                    cshared.Checked = currentField.IsShared;
                    cunversioned.Checked = currentField.IsUnversioned;
                    cblob.Checked = currentField.IsBlob;
                }
                field.Controls.Add(cname);
                field.Controls.Add(ctype);
                field.Controls.Add(cshared);
                field.Controls.Add(cunversioned);
                field.Controls.Add(cblob);
            }
            else
            {
                Label noField = new Label() { Header = "Field has been deleted." };
                noField.Style.Add("color", "red");
                noField.ID = "noField_" + id.ToString();
                field.Controls.Add(noField);
            }
            

            ControlArchived.Controls.Add(field);
            Control.Controls.Add(archivedfield);
            
            
        }
        protected override void OnOK(object sender, EventArgs args)
        {
            base.OnOK(sender, args);
            ((Archive)this.Archive).RestoreItem(this.ArchivalId);
        }
    }
}
